package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    public static final String APP_ID = "appid";
    public static final String SECRET = "secret";
    public static final String JS_CODE = "js_code";
    public static final String GRANT_TYPE = "grant_type";
    public static final String GRANGRANT_TYPET_VALUE = "authorization_code";

    public static final String WX_LOGINURL = "https://api.weixin.qq.com/sns/jscode2session";


    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;


    /**
     * 微信小程序登陆
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //获得openid，来判断是否登陆成功，和判断是否是新用户
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put(APP_ID, weChatProperties.getAppid());
        paramMap.put(SECRET, weChatProperties.getSecret());
        paramMap.put(JS_CODE, userLoginDTO.getCode());
        paramMap.put(GRANT_TYPE, GRANGRANT_TYPET_VALUE);

        String json = HttpClientUtil.doGet(WX_LOGINURL, paramMap);

        //获取openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        //检验用户是否存在
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //检查用户是否是新用户
        User user = userMapper.wxLogin(openid);


        //如果是新用户那么就注册信息，把已有的信息注册了，剩下的等用户自己完善
        if (user == null) {
//            user =new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.saveUser(user);
        }

        //如果是老用户，那么返回查找的用户值给Controller
        return user;
    }
}
